import React, { useEffect, useState } from 'react';
import { Button, Card, Divider, Empty, message, Modal, Skeleton, Space, Spin, Tag, Typography } from 'antd';
import BraftEditor, { EditorState } from 'braft-editor';
import {
  ArticleNormalCategory,
  ArticleStatus,
  articleStatus,
  articleStatusColor,
  FileGroup
} from "common/utils/data";
import {
  completeAllImgUrl,
  deleteAllImgUrl,
  getRichTextArticleTitleCategoryPrefix
} from "common/utils/utils";
import Editor from "@/components/Editor";
import { useRequest } from "ahooks";
import { articleV1ControllerShowMine, articleV1ControllerUpdateMine } from "@/services/auto/article";

const { Title } = Typography;

export default function EditorArea(props){
  const {
    setDrawerVisible,
    activeArticleUuid,
    setActiveArticleUuid,
    setEdited,
    edited,
    beforeSave,
    refreshEditor,
    refreshList,
  } = props;

  const {
    data: getArticlesDetailData,
    loading: getArticlesDetailLoading,
    refresh: getArticlesDetailRefresh,
    runAsync: getArticlesDetailRun,
    mutate: getArticlesDetailMutate,
  } = useRequest(articleV1ControllerShowMine, {
    manual: true,
    onSuccess: res=>{
      setEditorState(BraftEditor.createEditorState(completeAllImgUrl(res.ext.contentRaw, true)));
    }
  });
  useEffect(()=>{
    refreshEditor.current = getArticlesDetailRefresh;
  },[getArticlesDetailRefresh])

  useEffect(()=>{
    if(activeArticleUuid){
      getArticlesDetailRun({uuid: activeArticleUuid});
    }
  },[activeArticleUuid]);

  const {run: patchArticlesRun,loading: patchArticlesLoading} = useRequest(articleV1ControllerUpdateMine, {
    manual: true,
    onSuccess: (res, [_, req])=>{
      setEdited(false);
      refreshList.current?.();
      // 提交审核情况
      if(req?.status === ArticleStatus.REVIEW){
        message.success({
          content: '提交审核成功，管理员审核通过后自动发布',
        })
        getArticlesDetailMutate(origin=>{
          return {
            ...origin,
            status: ArticleStatus.REVIEW,
          }
        })
      }else {
        message.success({
          content: '保存成功'
        })
        getArticlesDetailMutate(origin=>{
          return {
            ...origin,
            status: ArticleStatus.DRAFT,
          }
        })
      }

    }
  })

  const [editorState, setEditorState] = useState<EditorState>();

  const submitContent = () => {
    if(activeArticleUuid){
      beforeSave(getArticlesDetailData?.status).then(()=>{
        patchArticlesRun({uuid: activeArticleUuid},{
          content: deleteAllImgUrl(editorState.toHTML()),
          contentRaw: deleteAllImgUrl(editorState.toRAW(), true),
        });
      });
    }
  }

  return <Card className="h-full relative" classNames={{body: 'h-full'}} bordered={false}>
    {(()=>{
      if(!activeArticleUuid){
        return <div className="h-full flex items-center justify-center">
          <Empty description={<>请选择文章 或 <Button
            type="link"
            className="px-0"
            onClick={() => {
              setActiveArticleUuid(null);
              setDrawerVisible(true);
            }}
          >
            创建文章
          </Button></>}
          />
        </div>;
      }

      if(getArticlesDetailLoading){
        return <Skeleton active />
      }

      return (<div className={`h-full flex flex-col`}>
        <div className={`flex justify-between`}>
          <div className="flex items-center">
            {!!getArticlesDetailData && <>
              <Tag
                color={articleStatusColor[ getArticlesDetailData.status ]}
              >
                {articleStatus[ getArticlesDetailData.status ]}
              </Tag>
              <Title level={4} className="mb-0">
                {getArticlesDetailData.categories.map(it=>{
                  return getRichTextArticleTitleCategoryPrefix(it as ArticleNormalCategory)
                }).join('')} {getArticlesDetailData?.title}
              </Title>
            </>}
          </div>
          <Space>
            <Button
              type="primary"
              disabled={!edited}
              loading={patchArticlesLoading}
              onClick={()=>{
                submitContent();
              }}
            >
              保存
            </Button>
            {
              [ArticleStatus.DRAFT, ArticleStatus.REJECT].includes(getArticlesDetailData?.status as ArticleStatus) && <Button
                type="primary"
                ghost
                loading={patchArticlesLoading}
                onClick={() => {
                  Modal.confirm({
                    content: '确定要提交审核吗？提交后可以撤回',
                    onOk: ()=>{
                      return patchArticlesRun({uuid: activeArticleUuid},{
                        status: ArticleStatus.REVIEW,
                        content: deleteAllImgUrl(editorState.toHTML()),
                        contentRaw: deleteAllImgUrl(editorState.toRAW(), true),
                      })
                    }
                  })
                }}
              >
                提交审核
              </Button>}
            {
              getArticlesDetailData?.status === ArticleStatus.REVIEW && <Button
                type="primary"
                ghost
                danger
                loading={patchArticlesLoading}
                onClick={() => {
                  Modal.confirm({
                    centered: true,
                    content: '确定要撤回审核吗？',
                    onOk: ()=>{
                      return patchArticlesRun({uuid: activeArticleUuid},{
                        status: ArticleStatus.DRAFT,
                      })
                    }
                  })
                }}
              >
                撤回审核
              </Button>
            }
            {
              getArticlesDetailData?.status === ArticleStatus.PUBLISH && <Button
                type="primary"
                ghost
                danger
                loading={patchArticlesLoading}
                onClick={() => {
                  Modal.confirm({
                    centered: true,
                    content: '确定要下架文章吗？',
                    onOk: ()=>{
                      return patchArticlesRun({uuid: activeArticleUuid},{
                        status: ArticleStatus.DRAFT,
                      })
                    }
                  })
                }}
              >
                下架文章
              </Button>
            }
            <Button
              type="primary"
              ghost
              onClick={() => {
                setDrawerVisible(true);
              }}
            >
              编辑文章基本信息
            </Button>
          </Space>
        </div>
        <Divider />
        <div className="flex-1 min-h-0">
          <Editor
            value={editorState}
            fileGroup={FileGroup.ARTICLE}
            onChange={(newEditorState)=>{
              setEditorState(newEditorState);
              setEdited(true);
            }}
            className={`flex flex-col`}
            contentClassName="flex-1 min-h-100"
            onSave={()=>{
              if(patchArticlesLoading){
                return;
              }
              submitContent();
            }}
          />
        </div>
      </div>);
    })()}
  </Card>
};
